<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel过滤去重工具</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            margin: 20px 0;
            transition: border-color 0.3s;
        }
        .upload-area:hover {
            border-color: #007bff;
        }
        .upload-area.dragover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        input[type="file"] {
            margin: 20px 0;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .progress {
            width: 100%;
            height: 20px;
            background-color: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
            margin: 20px 0;
            display: none;
        }
        .progress-bar {
            height: 100%;
            background-color: #007bff;
            width: 0%;
            transition: width 0.3s;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            display: none;
        }
        .result.success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .result.error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .statistics {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 15px;
            border-radius: 5px;
            margin-top: 20px;
        }
        .statistics h3 {
            margin-top: 0;
            color: #495057;
        }
        .stat-item {
            display: flex;
            justify-content: space-between;
            margin: 5px 0;
            padding: 5px 0;
            border-bottom: 1px solid #e9ecef;
        }
        .stat-item:last-child {
            border-bottom: none;
        }
        .stat-label {
            font-weight: bold;
        }
        .stat-value {
            color: #007bff;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Excel过滤去重工具</h1>
        
        <div class="info">
            <h3>功能说明</h3>
            <ul>
                <li><strong>过滤功能</strong>：删除还款状态为-1的订单</li>
                <li><strong>去重功能</strong>：按订单号和期数去重，保留最新数据</li>
                <li><strong>导出功能</strong>：保持原有字段顺序导出Excel文件</li>
            </ul>
        </div>

        <div class="upload-area" id="uploadArea">
            <p>拖拽Excel文件到此处，或点击选择文件</p>
            <input type="file" id="fileInput" accept=".xlsx,.xls" style="display: none;">
            <button type="button" onclick="document.getElementById('fileInput').click()">选择文件</button>
        </div>

        <div id="fileInfo" style="display: none;">
            <p><strong>已选择文件：</strong><span id="fileName"></span></p>
            <p><strong>文件大小：</strong><span id="fileSize"></span></p>
        </div>

        <div style="text-align: center;">
            <button id="processBtn" onclick="processFile()" disabled>处理并下载</button>
            <button id="processToDirBtn" onclick="processFileToDirectory()" disabled>处理并导出到目录</button>
            <button id="statisticsBtn" onclick="getStatistics()" disabled>获取统计信息</button>
        </div>

        <div id="outputDirSection" style="display: none; margin: 20px 0;">
            <label for="outputDirInput">输出目录：</label>
            <input type="text" id="outputDirInput" value="C:\AAAAmessage\" style="width: 300px; padding: 5px;">
            <button type="button" onclick="browseDirectory()">浏览</button>
        </div>

        <div class="progress" id="progress">
            <div class="progress-bar" id="progressBar"></div>
        </div>

        <div class="result" id="result"></div>

        <div class="statistics" id="statistics" style="display: none;">
            <h3>处理统计信息</h3>
            <div id="statisticsContent"></div>
        </div>
    </div>

    <script>
        const fileInput = document.getElementById('fileInput');
        const uploadArea = document.getElementById('uploadArea');
        const processBtn = document.getElementById('processBtn');
        const processToDirBtn = document.getElementById('processToDirBtn');
        const statisticsBtn = document.getElementById('statisticsBtn');
        const result = document.getElementById('result');
        const progress = document.getElementById('progress');
        const progressBar = document.getElementById('progressBar');
        const statistics = document.getElementById('statistics');
        const statisticsContent = document.getElementById('statisticsContent');

        let selectedFile = null;

        // 文件选择事件
        fileInput.addEventListener('change', function(e) {
            handleFile(e.target.files[0]);
        });

        // 拖拽事件
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            handleFile(e.dataTransfer.files[0]);
        });

        function handleFile(file) {
            if (!file) return;

            // 验证文件类型
            if (!file.name.match(/\.(xlsx|xls)$/i)) {
                showResult('请选择Excel文件(.xlsx或.xls)', 'error');
                return;
            }

            // 验证文件大小（100MB限制）
            if (file.size > 100 * 1024 * 1024) {
                showResult('文件大小不能超过100MB', 'error');
                return;
            }

            selectedFile = file;
            
            // 显示文件信息
            document.getElementById('fileName').textContent = file.name;
            document.getElementById('fileSize').textContent = formatFileSize(file.size);
            document.getElementById('fileInfo').style.display = 'block';
            
            // 启用按钮
            processBtn.disabled = false;
            processToDirBtn.disabled = false;
            statisticsBtn.disabled = false;
            
            // 显示输出目录选择
            document.getElementById('outputDirSection').style.display = 'block';
            
            // 隐藏之前的结果
            result.style.display = 'none';
            statistics.style.display = 'none';
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function showResult(message, type) {
            result.textContent = message;
            result.className = 'result ' + type;
            result.style.display = 'block';
        }

        function showProgress(show) {
            progress.style.display = show ? 'block' : 'none';
            if (show) {
                progressBar.style.width = '0%';
            }
        }

        function updateProgress(percent) {
            progressBar.style.width = percent + '%';
        }

        async function processFile() {
            if (!selectedFile) {
                showResult('请先选择文件', 'error');
                return;
            }

            const formData = new FormData();
            formData.append('file', selectedFile);

            showProgress(true);
            processBtn.disabled = true;
            statisticsBtn.disabled = true;

            try {
                const response = await fetch('/api/excel-filter-dedup/process', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    // 下载文件
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = selectedFile.name.replace(/\.(xlsx|xls)$/i, '_去重_' + new Date().toISOString().slice(0,19).replace(/:/g, '-') + '.xlsx');
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    
                    showResult('文件处理完成并已下载', 'success');
                } else {
                    const errorText = await response.text();
                    showResult('处理失败: ' + errorText, 'error');
                }
            } catch (error) {
                showResult('处理失败: ' + error.message, 'error');
            } finally {
                showProgress(false);
                processBtn.disabled = false;
                processToDirBtn.disabled = false;
                statisticsBtn.disabled = false;
            }
        }

        async function processFileToDirectory() {
            if (!selectedFile) {
                showResult('请先选择文件', 'error');
                return;
            }

            const outputDir = document.getElementById('outputDirInput').value.trim();
            if (!outputDir) {
                showResult('请输入输出目录', 'error');
                return;
            }

            const formData = new FormData();
            formData.append('file', selectedFile);
            formData.append('outputDir', outputDir);

            showProgress(true);
            processBtn.disabled = true;
            processToDirBtn.disabled = true;
            statisticsBtn.disabled = true;

            try {
                const response = await fetch('/api/excel-filter-dedup/process-to-directory', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    showResult(`文件处理完成！已导出到: ${data.outputFilePath}`, 'success');
                } else {
                    showResult('处理失败: ' + data.message, 'error');
                }
            } catch (error) {
                showResult('处理失败: ' + error.message, 'error');
            } finally {
                showProgress(false);
                processBtn.disabled = false;
                processToDirBtn.disabled = false;
                statisticsBtn.disabled = false;
            }
        }

        function browseDirectory() {
            // 注意：由于浏览器安全限制，无法直接选择目录
            // 这里只是提示用户手动输入路径
            alert('由于浏览器安全限制，请手动输入输出目录路径。\n默认路径：C:\\AAAAmessage\\');
        }

        async function getStatistics() {
            if (!selectedFile) {
                showResult('请先选择文件', 'error');
                return;
            }

            const formData = new FormData();
            formData.append('file', selectedFile);

            statisticsBtn.disabled = true;

            try {
                const response = await fetch('/api/excel-filter-dedup/statistics', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    const stats = data.statistics;
                    statisticsContent.innerHTML = `
                        <div class="stat-item">
                            <span class="stat-label">总行数：</span>
                            <span class="stat-value">${stats.totalCount}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">过滤行数：</span>
                            <span class="stat-value">${stats.filteredCount}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">重复行数：</span>
                            <span class="stat-value">${stats.duplicateCount}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">最终行数：</span>
                            <span class="stat-value">${stats.finalCount}</span>
                        </div>
                    `;
                    statistics.style.display = 'block';
                    showResult('统计信息获取成功', 'success');
                } else {
                    showResult('获取统计信息失败: ' + data.message, 'error');
                }
            } catch (error) {
                showResult('获取统计信息失败: ' + error.message, 'error');
            } finally {
                statisticsBtn.disabled = false;
            }
        }
    </script>
</body>
</html>
